﻿using I_Authorization.Domains;
using I_Authorization.Domains.Organization;
using I_Authorization.Domains.RBAC;
using I_Authorization.Infrastructure.Interface;
using I_Authorization.Infrastructure.Migrations;
using I_Authorization.Read.API.Application.CommandHandlers.Role;
using I_Authorization.Read.API.Application.Commands.Permission;
using MediatR;
using System.Linq;

namespace I_Authorization.Read.API.Application.CommandHandlers.Permission
{
    /// <summary>
    /// 权限分页
    /// </summary>
    public class PermissionShowPageCommandHandlers : IRequestHandler<PermissionShowPageCommand, Page<ShowPermissionRoleDTO>>
    {
        private readonly IPermissionRepository _permissionRepository;  //调用全是底层方法
        private readonly IRoleRepository _roleRepository;     //调用角色底层方法

        public PermissionShowPageCommandHandlers(IPermissionRepository permissionRepository,IRoleRepository roleRepository)
        {
            _permissionRepository = permissionRepository;
            _roleRepository = roleRepository;
        }

        /// <summary>
        /// 权限分页展示
        /// </summary>
        /// <param name="request"></param>
        /// <param name="cancellationToken"></param>
        /// <returns></returns>
        public async Task<Page<ShowPermissionRoleDTO>> Handle(PermissionShowPageCommand request, CancellationToken cancellationToken)
        {
            //var list = await _permissionRepository.GetAsync(x=>x.IsDel==true);

            var list = (from a in await _permissionRepository.GetAllAsync()
                        join b in await _roleRepository.GetAllAsync() on a.RoleId equals b.RoleId
                        where a.IsDel == true
                        && (string.IsNullOrEmpty(request.FunctionName) || a.FunctionName.Contains(request.FunctionName))
                        select new ShowPermissionRoleDTO
                        {
                            PermissionId = a.PermissionId,
                            FunctionName = a.FunctionName,
                            Operation = a.Operation,
                            RoleId = a.RoleId,
                            RoleName = b.RoleName,
                            RoleRemark = b.RoleRemark,
                            RoleDescription = b.RoleDescription
                        }).ToList();

            int totalCount = list.Count();
            int pageCount = (int)Math.Ceiling(totalCount * 1.0 / request.pageSize);
            list=list.Skip((request.pageIndex-1)*request.pageSize).Take(request.pageSize).ToList();
            //throw new NotImplementedException();
            return new Page<ShowPermissionRoleDTO>
            {
                tatalCount = totalCount,
                pageCount = pageCount,
                Data = list,
            };
        }
    }
}
